
<script setup lang="ts">
import { defineProps, defineEmits, computed, ref, onMounted, onUnmounted} from 'vue';

const emit = defineEmits(['update:value', 'change']); // 定义发出的事件

const props = defineProps({
  label: {
    type: String,
    default: ''
  },
  options: {
    type: Array,
    required: true
  },
  value: { // 注意这里使用 'value' 而不是 'selectedValue'
    type: [String, Number],
    default: null // 你可以根据需要设置默认值，比如某个特定的选项值
  }
});

// 使用 computed 来处理 v-model 的双向绑定
// const selectedValue = computed({
//   get() {
//     return props.value;
//   },
//   set(newValue) {
//     emit('update:value', newValue); // 当 selectedValue 改变时，发出 update:value 事件
//   }
// });


const selectedItem = ref('');
const isDropdownVisible = ref(false);
const selectRef = ref<HTMLElement | null>(null);

const toggleDropdown = () => {
  isDropdownVisible.value = !isDropdownVisible.value;
};

const selectItem = (value:any) => {
   selectedItem.value = value.text;
  isDropdownVisible.value = false;
  // 触发自定义事件将选中的值传递给父组件
  emit('change', value.value);
};


// 监听全局点击事件
const handleOutsideClick = (event: MouseEvent) => {
  if (isDropdownVisible.value && !selectRef.value?.contains(event.target as Node)) {
    isDropdownVisible.value = false;
  }
};

onMounted(() => {
  if (props.options.length == 0) {
    selectedItem.value = "请选择"
  } else {
    selectedItem.value = props.options[0].text
  }
 document.addEventListener('click', handleOutsideClick);
});

onUnmounted(() => {
  document.removeEventListener('click', handleOutsideClick);
});

</script>

<template>
  <div class="custom-select"  ref="selectRef">
    <div class="selected-item" @click="toggleDropdown">
      {{selectedItem}}
    </div>
    <div class="dropdown" v-if="isDropdownVisible" @click.stop>
      <div
          v-for="option in options"
          :key="option.value"
          class="dropdown-item"
          @click="selectItem(option)"
      >
        {{ option.text }}
      </div>
    </div>
  </div>

</template>

<style scoped>
.custom-select {
  position: relative;
}

.selected-item {
  padding: 10px;
  text-align: center;
  cursor: pointer;
  box-shadow: 0 0 2px #2F80ED;
  border-radius: 5px;
  width: 100%;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  background-color: #fff;
  box-shadow: 0 0 4px #2F80ED;
  z-index: 2;
}

.dropdown-item {
  padding: 10px;
  text-align: center;
  cursor: pointer;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.dropdown-item:hover {
  background-color: #2F80ED;
}
</style>



